package com.runmi.webchat.aftersale.common.utils;

import okhttp3.*;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: myx
 * @Date: create in 2017/12/12 10:38
 * @Description:
 */
public class OkHttpUtil {

    private static final String CHARSET_UTF_8 = "utf-8";

    private static final String CHARSET_GBK_8 = "gbk";

    public static final long CONNECT_TIMEOUT = 10000;

    public static final long READ_TIMEOUT = 10000;



    private static OkHttpClient client = null;

    static {
       // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("118.31.5.206", 21));;

        client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 带参POST请求
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String doPost(String url,
                                Map<String, String> params) {
        String responseBody = null;

        FormBody.Builder formBuilder = new FormBody.Builder();
        if(!CollectionUtils.isEmpty(params)) {
            params.forEach((key, value) -> {
                formBuilder.add(key, value);
            });
        }

        FormBody formBody = formBuilder.build();

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .url(url)
                .post(formBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            responseBody = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    /**
     * 带参GET请求
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, String> headers,
                               Map<String, String> params) {
        String responseBody = null;

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .url(attachParam(url,formatParams(params)))
                .headers(Headers.of(headers))
                .get()
                .build();

        try {
            Response response = client.newCall(request).execute();
            responseBody = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return responseBody;
    }

    /**
     * 无参GET请求
     * @param url
     * @param headers
     * @return
     */
    public static String doGet(String url) {
        String responseBody = null;

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .url(url)
                .get()
                .build();

        try {
            Response response = client.newCall(request).execute();
            responseBody = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return responseBody;
    }

    /**
     * 拼接url地址和参数
     * @param url
     * @param paramStr
     * @return
     */
    public static String attachParam(String url, String paramStr) {
        if(paramStr == null) {
            return url;
        }
        if(url.indexOf("?") > 0) {
            return url + "&" + paramStr;
        }
        return url + "?" + paramStr;

    }

    /**
     * 转义处理请求参数
     * @param params
     * @return
     */
    public static String formatParams(Map<String, String> params) {
        if(CollectionUtils.isEmpty(params)) {
            return null;
        }

        List<String> paramKeys = new ArrayList<>(params.keySet());
        Collections.sort(paramKeys);

        List<NameValuePair> valuePairs = new ArrayList<>();
        for (String key :paramKeys) {
            NameValuePair value = new BasicNameValuePair(key, params.get(key));
            valuePairs.add(value);
        }
        return URLEncodedUtils.format(valuePairs, CHARSET_UTF_8);
    }
}
